package com.lld.im.service.utils;

import com.alibaba.fastjson.JSONObject;
import com.lld.im.common.constants.Constants;
import com.lld.im.common.model.UserSession;
import org.apache.catalina.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.converter.StringHttpMessageConverter;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

/**
 * 获得redis种保存的用户数据
 */
@Component
public class RedisUserSessionUtils {


    @Autowired
    private StringRedisTemplate redisTemplate;

    /**
     * 获得用户在服务端的所有session
     * @param appId
     * @param userId
     * @return
     */
    public List<UserSession> getAllUserSession(Integer appId,String userId){
        String redisKey=appId+ Constants.RedissonConfig.USER_SESSION_KEY+userId;
        /* appId+''+userId ->(clientType+imei):(userSessionStr) */
        Collection<Object> values = redisTemplate.opsForHash().entries(redisKey).values();
        List<UserSession> list=new ArrayList<>();
        for (Object value : values) {
            String sessionStr=value.toString();
            list.add(JSONObject.parseObject(sessionStr,UserSession.class));
        }
        return list;
    }


    public UserSession getSingleUserSession(Integer appId,String userId,Integer clientType,String imei){
        String redisKey=appId+ Constants.RedissonConfig.USER_SESSION_KEY+userId;
        String hashKey=clientType+":"+imei;
        redisTemplate.opsForHash().get(redisKey,hashKey);
        Object o = redisTemplate.opsForHash().get(redisKey, hashKey);
        return JSONObject.parseObject(o.toString(),UserSession.class);
    }
    //TODO 获得除了本端以外的其他客户端的userSession

    /**
     * 保存用户当前登录的所有端信息
     * @param userSession
     */
    public void saveUserSession(UserSession userSession){
        String redisKey= userSession.getAppId()+ Constants.RedissonConfig.USER_SESSION_KEY+userSession.getUserId();
        String hashKey=userSession.getClientType()+":"+userSession.getImei();
        redisTemplate.opsForHash().put(redisKey,hashKey,JSONObject.toJSONString(userSession));
    }




}
